package cn.edu.lingnan.lsqn.controller;

import java.util.Date;
import java.util.Properties;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.cdahua.basic.model.Pager;
import cn.cdahua.basic.model.SystemContext;
import cn.edu.lingnan.lsqn.model.Article;
import cn.edu.lingnan.lsqn.model.ArticleType;
import cn.edu.lingnan.lsqn.model.LsqnException;
import cn.edu.lingnan.lsqn.model.User;
import cn.edu.lingnan.lsqn.service.IArticleService;
import cn.edu.lingnan.lsqn.util.MailUtil;
import cn.edu.lingnan.lsqn.util.PropertiesUtil;

@Controller
@RequestMapping("/article")
public class ArticleController {

	@Autowired
	private IArticleService articleService;

	@RequestMapping("/")
	public String list() {
		return "article/article";
	}

	@RequestMapping("/list")
	public String listAll(Model model, HttpSession session) {
		Pager<Article> articles = getDatas(session);
		model.addAttribute("datas", articles);
		return "comm/list";
	}

	@RequestMapping("/list/unread")
	public String listUnRead(Model model, HttpSession session) {
		Pager<Article> articles = getDatas(session, ArticleType.UNREAD);
		model.addAttribute("datas", articles);
		return "comm/list";
	}

	@RequestMapping("/list/unaccept")
	public String listIsRead(Model model, HttpSession session) {
		Pager<Article> articles = getDatas(session, ArticleType.UNACCEPT);
		model.addAttribute("datas", articles);
		return "comm/list";
	}

	@RequestMapping("/list/accept")
	public String listAccepted(Model model, HttpSession session) {
		Pager<Article> articles = getDatas(session, ArticleType.ACCEPT);
		model.addAttribute("datas", articles);
		return "comm/list";
	}

	@RequestMapping("/read/{id}")
	public String read(@PathVariable int id,Model model) {
		model.addAttribute("article", articleService.load(id));
		return "article/read";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(Article article, HttpSession session) {
		User u = (User) session.getAttribute("loginUser");
		if (u != null)
			article.setUser(u);
		articleService.add(article);
		Properties prop = PropertiesUtil.getAdminProp();
		String receiver = prop.getProperty("admin");
		sendMail(receiver, null,u.getEmail());
		return "redirect:/article/list";
	}
	
	@RequestMapping(value="/update/{id}",method=RequestMethod.GET)
	public String update(@PathVariable int id,Model model){
		Article a = articleService.load(id);
		model.addAttribute("article", a);
		return "article/update";
	}
	@RequestMapping(value="/update/{id}",method=RequestMethod.POST)
	public String update(Article newA,Model model){
		Article oldA = articleService.load(newA.getId());
		oldA.setContent(newA.getContent());
		oldA.setTitle(newA.getTitle());
		articleService.update(oldA);
		return "redirect:/article/list";
	}
	@RequestMapping(value="/update/{id}/{aType}")
	public String updateArticleType(@PathVariable int id,@PathVariable ArticleType aType,Model model){
		Article oldA = articleService.load(id);
		if(oldA.getStatus() == aType)
			return "redirect:/article/list";
		oldA.setStatus(aType);
		oldA.setReadDate(new Date());
		articleService.update(oldA);
		sendMail(oldA.getUser().getEmail(), oldA.getStatus(),null);
		return "redirect:/article/list";
	}
	@RequestMapping(value="/delete/{id}")
	public String delete(@PathVariable int id){
		articleService.delete(id);
		return "redirect:/article/list";
	}

	private Pager<Article> getDatas(HttpSession session) {
		Pager<Article> articles = null;
		SystemContext.setOrder("a.id");
		SystemContext.setSort("desc");
		try {
			if ((boolean) session.getAttribute("isStudent"))
				articles = articleService.findByUserId(((User) session.getAttribute("loginUser")).getId());
			else if ((boolean) session.getAttribute("isTeacher"))
				throw new LsqnException("权限错误");
			else
				articles = articleService.find();
		} finally {
			SystemContext.removeOrder();
			SystemContext.removeSort();
		}
		return articles;
	}

	private Pager<Article> getDatas(HttpSession session, ArticleType at) {
		Pager<Article> articles = null;
		SystemContext.setOrder("a.id");
		SystemContext.setSort("desc");
		if ((boolean) session.getAttribute("isStudent"))
			articles = articleService.findByUserIdAndStatus(((User) session.getAttribute("loginUser")).getId(), at);
		else if ((boolean) session.getAttribute("isTeacher"))
			throw new LsqnException("权限错误");
		else
			articles = articleService.findByStatus(at);
		
		SystemContext.removeOrder();
		SystemContext.removeSort();
		return articles;
	}
	
	private void sendMail(String receiver, ArticleType status,String u){
		String message = "";
		if(status==null){
			message = "收到"+u+"的投稿，请尽快审核！";
			MailUtil.sendMail(receiver, null, message);
			return;
		}
		if (status == ArticleType.ACCEPT)
			message = "您好！您向岭师青年投送的稿件已被采用，谢谢您对岭师青年的支持，期待您的下次投稿~";
		else if (status == ArticleType.UNACCEPT)
			message = "您好，您向岭师青年投送的稿件未通过审核，感谢您对岭师青年的支持，继续加油哦，说不定下次就行了，欢迎下次来稿~";
		else
			return;
		MailUtil.sendMail(receiver, null, message);
	}
}
